<template>
    <div>
      <el-scrollbar :style="{height: bodyHeight+'px'}">
      <el-form ref="formData" :model="formData"  :rules="rules" label-width="125px"  v-loading="loading" :element-loading-text="loadingText">
        <el-row type="flex" justify="space-around">
          <el-col :span="12">
            <el-form-item label="Cancelation Policy" label-width="150px" prop="cancellation_policy_category">
              <el-select placeholder="Please Select A Cancelation Policy" v-model="formData.cancellation_policy_category">
                <el-option label="Flexible" value="flexible"></el-option>
                <el-option label="Moderate" value="moderate"></el-option>
                <el-option label="Strict 14" value="strict_14_with_grace_period"></el-option>
                <el-option label="Strict 30" value="super_strict_30"></el-option>
                <el-option label="Strict 60" value="super_strict_60"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Istant Booking Allowed" label-width="165px"  prop="instant_booking_allowed_category">
              <el-select placeholder="Please Select A Istant Booking Allowed" v-model="formData.instant_booking_allowed_category">
                <el-option label="Everyone" value="everyone"></el-option>
                <el-option label="Experienced" value="experienced"></el-option>
                <el-option label="Government ID" value="government_id"></el-option>
                <el-option label="Experienced and Government ID" value="experienced_guest_with_government_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="Check-in Time" label-width="150px" prop="check_in_time_end">
              <el-switch v-model="startFlexible" @change="switchChange(1)">
              </el-switch>
              <el-input  placeholder="Please Enter Check In Time Start" style="width:26%;"
                         v-model="formData.check_in_time_start" :disabled="startFlexible"></el-input>
              <el-button type="text" disabled style="font-weight: bold;margin:0px 2px;">至</el-button>
              <el-switch v-model="endFlexible"  @change="switchChange(2)">
              </el-switch>
              <el-input  placeholder="Please Enter Check InTime End" style="width:26%;"
                         v-model="formData.check_in_time_end" :disabled="endFlexible"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Check-out Time" label-width="150px" prop="check_out_time">
                <el-input-number  placeholder="Please Enter Check Out Time" v-model="formData.check_out_time" :step="1" :min="0" :max="23"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="Instant Booking Message" label-width="185px"  prop="instant_book_welcome_message">
              <el-input  style="width:93%"
                type="textarea"
                :rows="3"
                placeholder="Please Enter Instant Booking Message"
                v-model="formData.instant_book_welcome_message">
              </el-input>
              </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">
          Listing Expectations
          <el-button type="primary" icon="el-icon-plus" circle  @click="addExpectation"></el-button>
<!--          <el-button type="success" icon="el-icon-finished" circle @click="saveExpectations"></el-button>-->
        </el-divider>
          <el-row type="flex" justify="space-around" style="border-bottom: 1px dashed lightgray;">
            <el-col :span="8">
              <div class="expectation-cmn-header">Type</div>
            </el-col>
            <el-col :span="12">
              <div class="expectation-cmn-header" >Details</div>
            </el-col>
            <el-col :span="4">
              <div class="expectation-cmn-header">&nbsp;</div>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" align="middle" style="margin: 10px 0px;" v-for="(item,index) in expectationsDatas">
            <el-col :span="8">
              <el-select placeholder="Please Select A Type" v-model="item.expectation_type" style="margin-left: 30px;">
                <el-option label="Requires Stairs" value="requires_stairs"></el-option>
                <el-option label="Potential Noise" value="potential_noise"></el-option>
                <el-option label="Has Pets" value="has_pets"></el-option>
                <el-option label="Limited Parking" value="limited_parking"></el-option>
                <el-option label="Shared Spaces" value="shared_spaces"></el-option>
                <el-option label="Limited Amenities" value="limited_amenities"></el-option>
                <el-option label="Surveillance" value="surveillance"></el-option>
                <el-option label="Weapons" value="weapons"></el-option>
                <el-option label="Animals" value="animals"></el-option>
              </el-select>
            </el-col>
            <el-col :span="14">
              <el-input  placeholder="Please Enter Details"  v-model="item.added_details" style="margin-left: 10px;width: 95%"></el-input>
            </el-col>
            <el-col :span="2">
              <el-button type="danger" icon="el-icon-delete" circle @click="delExpectation(index)"></el-button>
            </el-col>
          </el-row>

        <el-divider content-position="left"></el-divider>
        <el-row type="flex" justify="space-around" style="border-bottom: 1px dashed lightgray;">
          <el-col :span="8">
            <div class="expectation-cmn-header">Guest Controls</div>
          </el-col>
          <el-col :span="16">
            <div class="expectation-cmn-header" >Children Not Allowed Reason</div>
          </el-col>

        </el-row>
        <el-row type="flex" justify="center" align="middle" style="margin: 10px 0px;" >
          <el-col :span="8">
            <el-form-item label="Allow Children"   required>
              <el-switch v-model="guest_controls.allows_children_as_host" @change="changeChildren">
              </el-switch>
            </el-form-item>

            <el-form-item label="Allow Infants"   required>
              <el-switch v-model="guest_controls.allows_infants_as_host">
              </el-switch>
            </el-form-item>

            <el-form-item label="Allow Smoking"   required>
              <el-switch v-model="guest_controls.allows_smoking_as_host">
              </el-switch>
            </el-form-item>

            <el-form-item label="Allow Pets"   required>
              <el-switch v-model="guest_controls.allows_pets_as_host">
              </el-switch>
            </el-form-item>

            <el-form-item label="Allow Events"   required>
              <el-switch v-model="guest_controls.allows_events_as_host">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-input  style="width:95%"
                       type="textarea"
                       :rows="12" :disabled="allowChildrenFlag"
                       placeholder="Please Enter Children Not Allowed Reason"
                       v-model="guest_controls.children_not_allowed_details">
            </el-input>
          </el-col>
        </el-row>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="doSave">Save Changes</el-button>
          <el-button @click="doClose">Close</el-button>
          <el-button type="danger"  @click="doSynchro">更新订房规则</el-button>
        </el-form-item>
      </el-form>
      </el-scrollbar>
    </div>
</template>

<script>
    import {addModel,searchModel,get,updateModel,deleteModel,addModels,updateModels} from "@/api/model";
    import {submitAction} from "@/api/task";

    export default {
        name: "EditBookingSettingsForm",
        props:["pid"],
        data() {
            return {
                model: 'PhysicalRoomBookingSettings', //模型（物理房间预订设置）
                model2: 'PhysicalRoomListingExpectationsForGuests',//
                model3: 'PhysicalRoomGuestControls',//
                bodyHeight:900,
                startFlexible:false,
                endFlexible:false,
                parentObj : null, //父对象
                loading:false,
                loadingText:'data load ...',
                formData: this.getInitFormData(),
                expectationsDatas:this.getInitExpectationsDatas(),
                guest_controls: this.getGuestControlsDatas(),
                rules: this.getInitRules(),
                allowChildrenFlag : false
            }
        },
        created() {
            const _bodyHeight = document.documentElement.clientHeight || document.body.clientHeight;
            // console.log("bodyHeight="+_bodyHeight);
            this.bodyHeight = _bodyHeight - 65;
        },
        mounted(){

        },
        methods: {
            getInitFormData(){
                return  {
                    id: null,
                    physical_room_hook: this.pid,//   Hook    PhysicalRoom的外链
                    cancellation_policy_category: null,//    Enum字符串
                    check_in_time_start: null,// 字符串 要么是FLEXIBLE，要么是数字8-25的字符串表现是形式。入住时间段开始。
                    check_in_time_end: null,//   字符串 要么是FLEXIBLE，要么是数字9-26的字符串表现是形式。入住时间段结束。
                    check_out_time: 0,//  整数  0-23。退房时间。
                    instant_booking_allowed_category: null,//    Enum字符串 谁可以即时预订
                    instant_book_welcome_message: null,//    字符串 即时预订成功后的欢迎语。最大199个字。
                    listing_expectations_for_guests_hook: null, //PhysicalRoomListingExpectationsForGuests的外链
                    guest_controls_hook: null, //  Hook    PhysicalRoomGuestControls的外链
                };
            },
            getInitExpectationsDatas(){
              return [];
               // return [{id:null, expectation_type:null,added_details:null}];
            },
            getGuestControlsDatas(){
                return  {
                    allows_children_as_host:true, //布尔值	是否允许儿童
                    allows_infants_as_host:true,  //布尔值	是否允许婴儿
                    children_not_allowed_details:'',//可选。最大300个字符。关于为什么不允许儿童的解释。allows_children_as_host为假时，需要填写。
                    allows_smoking_as_host:true,	//  布尔值	是否允许吸烟
                    allows_pets_as_host: true, //	布尔值	是否允许宠物
                    allows_events_as_host: true	//  布尔值	是否允许举办派对和活动
                };//  Hook    PhysicalRoomGuestControls的外链;
            },
            getInitRules() {
                const _this = this;
                const custRulesCfg = this.getCustRulesConfig();

                const checkInTimeEndValid = (rule, value, callback) => {
                    if(_this.startFlexible && _this.endFlexible){
                        callback();
                        return;
                    }
                    if(!_this.startFlexible) {
                        if (!_this.formData.check_in_time_start) {
                            callback(new Error('Please Enter Check In Time Start'));
                        } else {
                            try {
                                const _check_in_time_start = parseInt(_this.formData.check_in_time_start);
                                if (_check_in_time_start < 8 || _check_in_time_start > 25) {
                                    callback(new Error('Check In Time Start Must be an integer between 8 and 25'));
                                } else {
                                    callback();
                                }
                            } catch (e) {
                                callback(new Error('Check In Time Start Must be an integer value'));
                            }
                        }
                    }

                    if(!_this.endFlexible) {
                        if (!_this.formData.check_in_time_end) {
                            callback(new Error('Please Enter Check InTime End'));
                        } else {
                            try {
                                const _check_in_time_end = parseInt(_this.formData.check_in_time_end);
                                if (_check_in_time_end < 9 || _check_in_time_end > 26) {
                                    callback(new Error('Check InTime End Must be an integer between 9 and 26'));
                                } else {
                                    callback();
                                }
                            } catch (e) {
                                callback(new Error('Check InTime End Must be an integer value'));
                            }
                        }
                    }
                };

                const checkOutTimeValid = custRulesCfg.intValid('Check Out Time',0,23);

                return {
                    cancellation_policy_category:[
                        { required: true, message: 'Please Select A Cancelation Policy', trigger: 'change' }
                    ],
                    instant_booking_allowed_category:[
                        { required: true, message: 'Please Select A Istant Booking Allowed', trigger: 'change' }
                    ],
                    check_in_time_end:[
                        { required: true, validator:checkInTimeEndValid, trigger: 'blur' },
                    ],
                    check_out_time:[
                        { required: true, validator:checkOutTimeValid, trigger: 'blur' },
                    ],
                    instant_book_welcome_message: [
                        { required: true, message: 'Please Enter Instant Booking Message', trigger: 'blur' },
                        { min: 1, max: 199, message: '1 to 199 characters in length', trigger: 'blur' }
                    ],
                };
            },
            getCustRulesConfig(){
                return {
                    intValid: function(label, min, max){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseInt(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an integer value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an integer value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    callback();
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }
                        };
                        return intValidFun;
                    },
                    floatValid: function(label, min, max,custCb){
                        const intValidFun = (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('Please Enter '+label));
                            }
                            try{
                                value = parseFloat(value);
                            }catch (e) {
                                callback(new Error(label+' Must be an float value'));
                            }

                            if (!Number.isInteger(value)) {
                                callback(new Error(label+' Must be an float value'));
                            }
                            if(min != null && max != null){
                                if(value < min || value > max){
                                    callback(new Error(label+' Must be greater than or equal to '+min+' and less than or equal to '+max));
                                }else{
                                    if(custCb){
                                        custCb(rule, value, callback);
                                    }else{
                                        callback();
                                    }
                                }
                            }
                            if(min != null && max == null){
                                if (min && min > value) {
                                    callback(new Error(label+' Must be greater than or equal to '+min));
                                } else {
                                    callback();
                                }
                            }

                            if(max != null && min == null){
                                if (max && value > max) {
                                    callback(new Error(label+' Must be less than or equal to '+max));
                                } else {
                                    callback();
                                }
                            }

                        };
                        return intValidFun;
                    },
                };
            },
            changeChildren(value){
                console.log("changeChildren.value = "+value);
                this.allowChildrenFlag = value;
                if(value){
                    this.guest_controls.children_not_allowed_details = null;
                }
            },
            refresh(_parentObj){
                console.log("refresh to do ...");
                this.parentObj = _parentObj;
                this.loadDatas();
            },
            /**
             * 加载数据
             */
            loadDatas(){
                console.log("loadDatas to do ...");
                this.doReset();
                this.loadBookingSettings();
            },
            loadBookingSettings(){
                let _this = this;
                this.loading = true;
                const _pid = this.pid;
                const _parent = _this.parentObj || _this.$parent;
                searchModel(this.model, {
                    search_keys:{physical_room__physical_room_id: _pid}
                }).then(res => {
                    _this.loading = false;
                    if(!res || !res.data){
                        _this.doReset();
                        return;
                    }
                    const list = res.data.list;
                    if(!list  || list.length == 0){
                        _this.doReset();
                        return;
                    }
                    this.formData = list[0];
                    this.loadExpectationsForGuests();
                    this.loadGuestControls();
                }).catch(reason => {
                    _this.loading = false;
                    console.error(reason);
                });
            },
            loadExpectationsForGuests(){
                const _this = this;
                const idsStr = this.formData.listing_expectations_for_guests_hook;
                if(!idsStr){
                    this.expectationsDatas = this.getInitExpectationsDatas();
                    return;
                }
                let ids = idsStr.split(";");
                _this.loading = true;
                searchModel(this.model2, {
                    search_keys:{},raw_filter:{id__in: ids}
                }).then(res => {
                    _this.loading = false;
                    if(!res || !res.data){
                        this.expectationsDatas = this.getInitExpectationsDatas();
                        return;
                    }
                    const list = res.data.list;
                    if(!list  || list.length == 0){
                        this.expectationsDatas = this.getInitExpectationsDatas();
                        return;
                    }
                    this.expectationsDatas = list;
                }).catch(reason => {
                    _this.loading = false;
                    console.error(reason);
                });
            },
            loadGuestControls(){
                const _this = this;
                const _id = this.formData.guest_controls_hook;
                if(!_id){
                    this.guest_controls = this.getGuestControlsDatas();
                    return;
                }

                _this.loading = true;
                searchModel(this.model3, {
                    search_keys:{id: _id}
                }).then(res => {
                    _this.loading = false;
                    if(!res || !res.data){
                        this.guest_controls = this.getGuestControlsDatas();
                        return;
                    }
                    const list = res.data.list;
                    if(!list  || list.length == 0){
                        this.guest_controls = this.getGuestControlsDatas();
                        return;
                    }
                    this.guest_controls = list[0];
                }).catch(reason => {
                    _this.loading = false;
                    console.error(reason);
                });
            },
            /**
             * 点击Expectation
             */
            addExpectation(){
                const data = {id:null, expectation_type:null,added_details:null};
                this.expectationsDatas.push(data);
            },
            /**
             * 删除Expectation Item
             */
            delExpectation(index){
                const _this = this;
                console.log("index="+index);
                const expecData =  this.expectationsDatas[index];
                const id = expecData.id;
                if(!id){
                    this.expectationsDatas.splice(index, 1);
                    _this.$message({
                        type: 'info',
                        message: 'Delete Data Success!'
                    });
                    return;
                }

                _this.loading = true;
                deleteModel(this.model2, id).then(res => {
                    resolve(res)
                    _this.loading = false;
                    this.expectationsDatas.splice(index, 1);
                    _this.$message({
                        type: 'info',
                        message: 'Delete Data Success!'
                    });
                    console.log("delExpectation Success ...");
                }).catch(reason => {
                    reject(reason);
                    _this.loading = false;
                    console.log("delExpectation Failure ...");
                    console.log(reason);
                });
            },

            /**
             *
             * 保存数据
             */
            doSave(){
                console.log("doSave to do ...");
                const _this = this;
                console.log(this.formData);
                this.formData.physical_room_hook = this.pid;
                let _formData = this.formData;
                for(var key in _formData){
                    const val = _formData[key];
                    if(!val && (val !== 0 || val !== '0')){
                        delete _formData[key];
                    }
                }

                this.$refs['formData'].validate((valid) => {
                    if (valid) {
                        _this.loading = true;
                        this.saveExpectations(()=>{

                            this.saveGuestControlsDatas(()=>{
                                _this.saveBookingSettingsDatas(_formData);
                            });

                        });

                    } else {
                        console.log('error submit!!');
                        _this.$message.error('Please Check Input Form Data Has Errors!');
                        return false;
                    }
                });

            },
            /**
             * BookingSettings 数据保存
             * */
            saveBookingSettingsDatas(_formData){
                const _this = this;
                if(_this.formData.id){
                    updateModel(this.model, _this.formData.id, _formData).then(res => {
                        _this.loading = false;
                     // _this.doSynchro();
                        _this.$message({
                            type: 'info',
                            message: 'Save Data Success!'
                        });

                    }).catch(reason => {
                        _this.loading = false;
                        console.log("doSave Failure...");
                        console.log(reason);
                        //_this.$message.error('Please Check Input Form Data Has Errors!');
                    });
                }else{
                    const jsonStr =  JSON.stringify(_formData);
                    addModel(this.model, jsonStr).then(res => {
                        console.log(res);
                        const _id = res.data.id;
                        _this.formData.id = _id;
                        _this.loading = false;
                      //  _this.doSynchro();
                        _this.$message({
                            type: 'info',
                            message: 'Save Data Success!'
                        });

                    }).catch(reason => {
                        _this.loading = false;
                        console.log("doSave Failure...");
                        console.log(reason);
                        // _this.$message.error('Please Check Input Form Data Has Errors!');
                    });
                }
            },
            /**
             *
             * PhysicalRoomListingExpectationsForGuests 数据保存
             * */
            saveExpectations(callback){
                console.log("========== saveExpectations ========");
                const _expectationsDatas = this.expectationsDatas;
                if(!_expectationsDatas || _expectationsDatas.length == 0){
                    if(callback) callback();
                   return;
                }

                for(let i=0, count=_expectationsDatas.length; i<count; i++) {
                    const _item = _expectationsDatas[i];
                    const expectation_type = _item.expectation_type;
                    const added_details = _item.added_details;
                    let errInfo = null;
                    if (!expectation_type) {
                        errInfo = "Type on line " + (i + 1) + " cannot be empty";
                    }
                    if (!added_details) {
                        errInfo = "Details on line " + (i + 1) + " cannot be empty";
                    }
                    if (!expectation_type && !added_details) {
                        errInfo = "Type and Details on line " + (i + 1) + " cannot be empty";
                    }
                    if(errInfo){
                        this.$message.error("Listing Expectations: "+errInfo);
                        this.loading = false;
                        return;
                    }
                }


                const _this = this;
                let insertDatas = [];
                let updateDatas = [];
                let insertPromise = null;
                let updatePromise = null;
                let indexMapping = {};

                for(let i=0, count=_expectationsDatas.length; i<count; i++){
                    const _item = _expectationsDatas[i];
                    const _id = _item.id;
                    if(_id){
                        updateDatas[updateDatas.length] = _item;
                    }else{
                        const _index = insertDatas.length;
                        insertDatas[_index+""] = _item;
                        indexMapping[_index+""] = i;
                    }
                }


                if(insertDatas &&　insertDatas.length > 0){
                    insertPromise = new Promise((resolve,reject)=>{
                        addModels(this.model2, insertDatas).then(res => {
                            resolve(res)
                            _this.loading = false;
                            console.log("insertPromise doSave Success ...");
                        }).catch(reason => {
                            reject(reason);
                            _this.loading = false;
                            console.log("insertPromise doSave Failure ...");
                            console.log(reason);
                        });
                    });
                }



                if(updateDatas &&　updateDatas.length > 0){
                    updatePromise = new Promise((resolve,reject)=>{
                        updateModels(this.model2, updateDatas).then(res => {
                            resolve(res)
                            _this.loading = false;
                            console.log("updatePromise doSave Success ...");

                        }).catch(reason => {
                            reject(reason);
                            _this.loading = false;
                             console.log("updatePromise doSave Failure...");
                            console.log(reason);
                            //_this.$message.error('Please Check Input Form Data Has Errors!');
                        });
                    });
                }

                const methodArr = [];
                if(insertPromise) methodArr[methodArr.length] = insertPromise;
                if(updatePromise) methodArr[methodArr.length] = updatePromise;
                this.loading = true;

                Promise.all(methodArr).then(res=>{
                    console.log("====== Promise.all ======");
                    console.log(_expectationsDatas);
                   if(insertDatas && insertDatas.length>0) _this.updateExpectationsDatasIds(res[0], indexMapping);
                    if(callback){
                        callback();
                    }else{
                        _this.loading = false;
                        _this.$message({
                            type: 'info',
                            message: 'Save Data Success!'
                        });
                    }
                })
            },
            updateExpectationsDatasIds(resultResp, indexMapping){
                const _this = this;
                const idsArr = resultResp.data.ids;
                console.log("===== updateExpectationsDatasIds ====");
                console.log(_this.expectationsDatas);
                idsArr.forEach((item) => {
                    const index = item.index;
                    const id = item.id;
                    const dataIndex = indexMapping[index+""];
                    _this.expectationsDatas[dataIndex]["id"] = id;
                });
                // console.log("===updateExpectationsDatasIds ==");
                console.log(_this.expectationsDatas);
                let exForGuestIds = [];
                _this.expectationsDatas.forEach(item => {
                    const id = item.id;
                    exForGuestIds[exForGuestIds.length] = id;
                });
                const _exForGuestIds = exForGuestIds.join(";");
                this.formData.listing_expectations_for_guests_hook = _exForGuestIds;
                // console.log("listing_expectations_for_guests_hook="+ _exForGuestIds);
                // console.log(this.formData);
            },
            /**
             * PhysicalRoomGuestControls 数据保存
             * */
            saveGuestControlsDatas(callback){
                const _this = this;
                const _guest_controls = this.guest_controls;
                const _id = _guest_controls.id;
                this.loading = true;
                if(!_id){
                    addModel(this.model3, _guest_controls).then(res => {
                        const respData = res.data;
                        const pkId = respData.id;
                        console.log("pkId="+pkId);
                        _this.guest_controls.id = pkId;
                        _this.formData.guest_controls_hook = pkId;
                        if(callback){
                            callback();
                        }else{
                            _this.loading = false;
                        }
                        console.log("saveGuestControlsDatas doSave Success.......");
                    }).catch(reason => {
                        reject(reason);
                        _this.loading = false;
                        console.log("updatePromise doSave Failure...");
                        console.log(reason);
                        //_this.$message.error('Please Check Input Form Data Has Errors!');
                    });
                }else{
                    updateModel(this.model3, _id, _guest_controls).then(res => {
                        if(callback){
                            callback();
                        }else{
                            _this.loading = false;
                        }
                        console.log("saveGuestControlsDatas update success.......");
                    }).catch(reason => {
                        reject(reason);
                        _this.loading = false;
                        console.log("saveGuestControlsDatas update Failure...");
                        console.log(reason);
                        //_this.$message.error('Please Check Input Form Data Has Errors!');
                    });
                }
            },
            doClose(){
                const _parent = this.parentObj ||  this.$parent;
                console.log(_parent);
                _parent.closeDrawer();
            },
            /**
             * 重置表单
             */
            doReset(){
                this.allowChildrenFlag = false;
                this.formData = this.getInitFormData();
                if(this.$refs['formData']) this.$refs['formData'].resetFields();
            },
            switchChange(actionType){
                if(actionType == 1){
                  if(this.startFlexible){
                      this.formData.check_in_time_start = "FLEXIBLE";
                  }else{
                      this.formData.check_in_time_start = "";
                  }
                }else if(actionType == 2){
                    if(this.endFlexible){
                        this.formData.check_in_time_end = "FLEXIBLE";
                    }else{
                        this.formData.check_in_time_end = "";
                    }
                }
            },
          /**
           * ActionTask ABNB API 同步
           */
          doSynchro(){
            const _this = this;
            const _id = this.formData.id;
            if(!_id){
              _this.$message.error(this.model+' id is null,Please Check Data...!');
              return;
            }
            //create_update_listing_description
            const actionName = "create_update_booking_settings";
            this.loadingText = "Calling API: "+actionName+" ...";
            this.loading = true;

            submitAction(this.model, _id,actionName).then(res => {
              this.loading = false;
              _this.$notify({
                title: 'Success',
                message: this.model+' Id:'+ _id +' call API:'+actionName+' succeeded !',
                type: 'success'
              });

            }).catch(reason => {
              _this.loading = false;
              console.log("deleteModel Failure...");
              console.error(reason);
              let errMsg = reason.data || reason.statusText;

              _this.$notify.error({
                title: 'Error',
                message: 'API:'+actionName+'  call error ,Error Reason:['+errMsg+']'
              });
              //_this.$message.error('Please Check Input Form Data Has Errors!');
            });
          }
        }
    }
</script>

<style scoped>
  .form-wrap{
    padding: 0px 20px;
  }

  .input-size{
    width: 85%;
  }

  .expectation-cmn-header{
    height: 30px;
    line-height: 30px;
    font-weight: bold;
    text-align: center;
    color: #606266;
  }
</style>
